<?php

namespace sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Log;

class AliSms implements SmsBase
{
    /**
     * 发送验证码
     * @param string $phone
     * @param int $code
     * @return bool
     * @throws ClientException
     */
    public static function sendCode(string $phone, int $code): bool
    {
        if (empty($phone) || empty($code)) {
            return false;
        }
        AlibabaCloud::accessKeyClient(
            SmsConfigEnum::ALIYUN_ACCESS_KEY_ID,
            SmsConfigEnum::ALIYUN_ACCESS_KEY_SECRET)
            ->regionId(SmsConfigEnum::ALIYUN_REGION_ID)
            ->asDefaultClient();
        $templateParam = [
            'code' => $code
        ];
        try {
            $result = AlibabaCloud::rpc()
                ->product("Dysmsapi")
                ->version("20017-05-25")
                ->action("SendSms")
                ->method("POST")
                ->host("dysmsapi.aliyuncs.com")
                ->options([
                    'query' => [
                        'RegionId' => SmsConfigEnum::ALIYUN_REGION_ID,
                        'PhoneNumbers' => $phone,
                        'SignName' => SmsConfigEnum::ALIYUN_SIGN_NAME,
                        "TemplateCode" => SmsConfigEnum::ALIYUN_TEMPLATE_CODE,
                        "TemplateParam" => json_encode($templateParam)
                    ]
                ])->request();
            Log::info("alisms-sendCode-result" . json_encode($result->toArray()));
        } catch (ClientException $e) {
            Log::error("alisms-sendCode-ClientException" . $e->getErrorMessage());
            return false;
        } catch (ServerException $e) {
            Log::error("alisms-sendCode-ServerException" . $e->getErrorMessage());
            return false;
        }
        return true;
    }
}